package com.bdsy.api.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.sql.visitor.functions.Char;
import com.bdsy.api.dao.TokenMapper;
import com.bdsy.api.entity.Token;
import com.bdsy.api.service.TokenService;

/**
 * ClassName:UserServiceImpl
 * Description: TODO 添加描述.
 * @author   Administrator
 * @version  
 * @since    JDK 1.8
 */

@Service("tokenService")
public class TokenServiceImpl implements TokenService{

    @Autowired
    TokenMapper tokenMapper;
    
    private final static int EXPIRE = 3600 * 72; // 3天
    //private final static int EXPIRE = 36;
    
    public Token getAppTokenByUserid(String userId){
    	Token token = tokenMapper.selectAppTokenByUserid(userId);
    	return token;
    }
    
    public Token getToken(String token){
    	Token tt = tokenMapper.selectoToken(token);
    	return tt;
    }
    
	public void save(Token token){
		tokenMapper.insertToken(token);
	}
	
	public void update(Token token){
		tokenMapper.update(token);
	}
	
	@Override
	public Map<String, Object> createToken(String userId) {
		//生成一个token
	//	String token = UUID.randomUUID().toString().replace("-", String.valueOf(userId));
		String token = UUID.randomUUID().toString().replace("-","");
		//当前时间
		Date now = new Date();

		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

		//判断是否生成过token
		Token tokenEntity = tokenMapper.selectAppTokenByUserid(userId);
		if(tokenEntity == null){
			tokenEntity = new Token();
			tokenEntity.setUserId(userId);
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//保存token
			save(tokenEntity);
		}else{
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);
			tokenEntity.setUserId(userId);
			//更新token
			update(tokenEntity);
		}

		Map<String, Object> map = new HashMap<>();
		map.put("token", token);
		map.put("expire", EXPIRE);

		return map;
	}
	
}

